<template>
    <div class="member-menu">
        <a-spin :spinning="listLoading">
            <div class="member-list">
                <template>
                    <vue-scroll>
                        <div class="list-group">
                            <a-list
                                    class="list-content"
                                    itemLayout="horizontal"
                                    :dataSource="list"
                                    v-show="list.length"

                            >
                                <a-list-item class="member-list-item" slot="renderItem" slot-scope="item,index"
                                             @click.native="setGitInfo(item)">
                                    <span slot="actions">
                                        <a-icon type="check" class="m-l-sm" v-show="showCheck(item)"></a-icon>
                                     </span>
                                    <a-list-item-meta>
                                    <span class="tag-title" slot="title"><a-icon type="branches" class="m-l-sm" v-if="!item.isBranch" @click.stop="opengiturl(item.href, 'changesets')"></a-icon>{{item.name}}</span>
                                    </a-list-item-meta>
                                </a-list-item>
                            </a-list>
                        </div>
                    </vue-scroll>
                </template>
            </div>
        </a-spin>
    </div>
</template>

<script>
    import _ from 'lodash'
    import {del, edit, list, save} from "../../api/taskTag";
    import {setTag, taskToTags, read as readTask, edit as editTask} from "../../api/task";
    import {read as readProject, list as listProject} from "../../api/project";
    import moment from "moment";
    import {notice} from "@/assets/js/notice";
    import {checkResponse} from "../../assets/js/utils";

    export default {
        name: "taskTagMenu",
        props: {
            projectCode: {
                type: [String, Number],
                default() {
                    return ''
                }
            },
            taskCode: {
                type: [String, Number],
                default() {
                    return ''
                }
            },
            isCommit: {//选择后是否提交
                type: [Boolean],
                default() {
                    return true
                }
            },
        },
        data() {
            return {
                keyword: '',
                searching: false,
                listLoading: false,
                tags: [],
                list: [],
                listTemp: [],
                project:{},
                task:{},
                gitTooltip: {
                    item: {},
                    tsp: '',
                    style:{},
                },
            };
        },
        created() {
            this.init();
        },
        watch: {
            keyword() {
                this.search();
            }
        },
        methods: {
            init() {
                let promiesList = []
                this.listLoading = true;
                if (this.projectCode) {
                    promiesList.push(
                        readProject(this.projectCode).then(res => {
                            let project = res.data
                            this.project = project
                            this.gitTooltip.item = project

                            listProject({type:'branches:'+project.name+'/branches/'}).then(res => {
                                this.branches = res.data.branches.sort((a, b) => (b.lastCommitDate+b.name).localeCompare(a.lastCommitDate+a.name)).filter((e, index) => index < 3)
                                this.fixGitTooltipInfo()
                                this.branches.map(branch => {
                                    listProject({type:'changesets:'+project.name+'/branches/'+branch.name+'/changesets/?pageSize=20'}).then(res => {
                                        if(res.data.changesets) {
                                            
                                            branch.changesets = res.data.changesets
                                            this.fixGitTooltipInfo()
                                        }
                                    })
                                })
                            })
                        })
                    )
                }
                if (this.taskCode) {
                    promiesList.push(
                        readTask(this.taskCode).then(res => {
                            this.task = res.data
                            if(this.task.git_info) {
                                this.tags = JSON.parse(this.task.git_info)
                            } else {
                                this.tags = []
                            }
                        })
                    )
                }
                Promise.all(promiesList).then(() => {
                    this.listLoading = false;
                })
            },
            opengiturl(a,b,c,d,e,f) {
                return window.opengiturl(a,b,c,d,e,f)
            },
            fixGitTooltipInfoStep2() {
                this.fixGitTooltipInfoTimeout = null;
                this._fixGitTooltipInfo()
            },
            fixGitTooltipInfo() {
                if(this.fixGitTooltipInfoTimeout) {
                    return;
                }
                this.fixGitTooltipInfoTimeout = setTimeout(this.fixGitTooltipInfoStep2, 100)
            },
            _fixGitTooltipInfo(extra_line_count) {
                let project = this.gitTooltip.item
                let _list = []
                this.branches.filter((ele,index) => index < 5).map((branch, branchIndex) => {
                    if(branch.changesets) {
                        console.log('branch', branch.name)
                        _list.push({name:'【'+branch.name+'】', isBranch:1, id:branch.id})
                        let changesets_count = branch.changesets.filter((changeset, index) => index < 5 && (changeset.date && moment().diff(moment(changeset.date), 'days') < 30 || index < 2)).length
                        if(extra_line_count && branch.changesets.length > changesets_count) {
                            let changesets_count2 = changesets_count + extra_line_count
                            if(changesets_count2 > branch.changesets.length) {
                                changesets_count2 = branch.changesets.length
                            }
                            if(changesets_count2 > changesets_count) {
                                extra_line_count -= changesets_count2 - changesets_count
                            }
                            changesets_count = changesets_count2
                        }
                        branch.changesets.filter((changeset, index) => index < changesets_count).map( changeset => {
                            let author = (changeset.author||{}).name
                            if(author) {
                                author = author.split('/')[0]
                            }
                            let descriptionSimple = changeset.description
                            if(descriptionSimple.indexOf('Merge branch') == 0) {
                                let strs = (descriptionSimple+'').split('Merge branch')
                                let done = false
                                if(strs.length > 1) {
                                    strs = strs[1]
                                    let srcBranchs = strs.split(' of ')
                                    if(srcBranchs.length > 1) {
                                        let srcBranch = srcBranchs[0].trim()
                                        let destBranchs = srcBranchs[1].split(' into ')
                                        if(destBranchs.length > 1) {
                                            let destBranch = destBranchs[1].trim().split(' ')[0].split('\n')[0].split('\r')[0].trim()
                                            
                                            done = true
                                            if(descriptionSimple.indexOf('Conflicts:') >= 0) {
                                                descriptionSimple = '合并分支(有冲突)：' + srcBranch + ' -> ' + destBranch
                                            } else {
                                                descriptionSimple = '合并分支：' + srcBranch + ' -> ' + destBranch
                                            }
                                        }
                                    }
                                }
                            }
                            if(descriptionSimple.length > 40) {
                                descriptionSimple = descriptionSimple.substring(0, 40)+'...'
                            }
                            _list.push({name:author+'【'+ moment(changeset.date).format('M-D H:mm') + '】'+descriptionSimple,id:changeset.id, href:changeset._links.self.href})
                        }) 
                    }
                })
                this.list = _list
                if(_list.length) {
                    if(!extra_line_count) {
                        let line_count = _list.length
                        if(line_count < 20) {
                            this._fixGitTooltipInfo(20 - line_count)
                        }
                    }
                }
            },
            showCheck(tag) {
                if(tag.isBranch) {
                    return;
                }
                const index = this.tags.findIndex(item => item.id == tag.id)
                if (index !== -1) {
                    return true;
                }
            },
            checkTaskChange(tag) {
                const index = this.tags.findIndex(item => item.id == tag.id)
                if (index !== -1) {
                    if(this.task.done && !this.task.without_git_desc) {
                        let msg = '已完成任务不可直接清空git信息，请先取消完成（或设置无git信息的原因）'
                        notice({title: msg}, 'notice', 'warning', 5);
                        return -1;
                    }

                    this.tags.splice(index, 1);
                } else {
                    this.tags.push({
                        id: tag.id,
                        name: tag.name,
                        href: tag.href,
                    });
                }
                return 0
            },
            setGitInfo(tag) {
                if(tag.isBranch) {
                    return;
                }
                if(this.checkTaskChange(tag) == -1) {
                    return
                }
                if (this.isCommit) {
                    let task = {taskCode:this.taskCode}
                    if(this.tags.length) {
                        task.git_info = JSON.stringify(this.tags)
                    } else {
                        task.git_info = ''
                    }
                    editTask(task).then(res => {
                        this.$emit('change', tag)
                    })
                } else {
                    this.$emit('change', tag)
                }
            },
        }
    }
</script>
<style lang="less">
    .member-menu {
        width: 100%;
        height:100%;
        .member-list {
            height: 100%;
            .member-list-item {
                padding: 0 !important;
            }
        }
    }
</style>
